<?php
namespace Admin\Controller;
use Common\Controller\BackendController;
import("ITK.Itklib.itaoke_https");

class ArticleurlcaijiController extends BackendController
{
    public function _initialize()
    {
        parent::_initialize();
        $this->_mod = D('Article');
        $this->_cate_mod = D('ArticleCate');
        $this->_url_mod = D('ArticleUrl');
    }
    
    public function index(){
    	$this->display();
    }
    public function toutiao()
    {
        $this->display('toutiao');
    }
    public function clear()
    {
        parent::_list(D('ArticleUrl'), $pagesize = 50);
        $p = $this->_get('p', 'intval', 1);
        $this->assign('p', $p);
        if (IS_POST) {
            if ($_REQUEST['isok'] == '1') {
                $action = $this->_post('action', 'trim');
                if ('notpass' == $action) {
                    $where['status'] = '0';
                } elseif ('clear' == $action) {
                    $db_file = CONF_PATH . 'db.php';
                    $db = (require $db_file);
                    $sql = 'TRUNCATE TABLE ' . $db['DB_PREFIX'] . 'article_url';
                    $mes = M()->execute($sql);
                    $this->success(L('clear_success'));
                }
            //    $ids_list = $this->_mod->where($where)->select();
                $ids_list = $this->_mod->where($where)->getField('id',true);
            /*    $ids = '';
                foreach ($ids_list as $val) {
                    $ids .= $val['id'] . ',';
                }*/
                if (count($ids_list) !=0) {
                    M('Article')->where(array('id'=> array('in',$ids_list)))->delete();
                }
                $this->_mod->where($where)->delete();
                $this->success(L('clear_success'));
            } else {
                $this->success('确认是否要删除？', U('Articleurlcaiji/clear'));
            }
        } else {
            $this->display();
        }
    }
    public function setting()
    {
        if (IS_POST) {
            $keyword = $this->_post('keyword', 'trim');
            $page = $this->_post('page', 'trim');
            F('articleurl_setting', array('keyword' => $keyword, 'page' => $page));
            $this->collect();
        }
    }
    public function toutiao_setting()
    {
        if (IS_POST) {
            $cat = $this->_post('cat', 'trim');
            $id = $this->_post('pid', 'trim');
            $page = $this->_post('page', 'trim');
            if (!$id) {
                $this->ajaxReturn(0, '请选择淘宝头条分类！');
            }
            $map['id'] = $id;
            $toutiao = M('article_toutiao')->where($map)->field('name,cat,pid')->find();
            $pid = $toutiao['pid'];
            if ($pid == 0) {
                $keyword = '';
            } else {
                $keyword = $toutiao['name'];
            }
            F('toutiao_setting', array('cat' => $toutiao['cat'], 'keyword' => urlencode($keyword), 'page' => $page));
            $this->toutiao_collect();
        }
    }
    public function collect()
    {
        $source = '';
        if (false === ($setting = F('articleurl_setting'))) {
            $this->ajaxReturn(0, L('illegal_parameters'));
        }
        $p = $this->_get('p', 'intval', 1);
        $url = 'http://www.chong4.com.cn/tag.php?tag=' . $setting['keyword'] . '&mode=1&page=' . $p;
        if ($p == 1) {
            $totalcoll = 0;
            $order_num = 0;
        } else {
            $totalcoll = F('totalcoll');
            $order_num = F('order_num');
        }
        $coll = 0;
 
        $itaoke_https = new \itaoke_https();
        $itaoke_https->fetch($url);
        $source = $itaoke_https->results;
        if (!$source) {
            $source = file_get_contents($url);
        }
        $source = rtrim(ltrim(trim($source), '('), ')');
        $source = iconv('UTF-8', 'UTF-8//IGNORE', $source);
        if (strpos($source, '<div class="content">')) {
            $this->ajaxReturn(0, '该类目暂时没有特价商品');
        }
        if (preg_match_all('/<div class="textbox-title(.*?)<\\/div>/s', $source, $matchitem)) {
            for ($i = 0; $i < count($matchitem[1]); $i++) {
                $item = $matchitem[1][$i];
                $title = get_word($item, 'target="_blank">', '<\\/a>');
                $url = get_word($item, '<a href="', '" target="_blank');
                $itemarray['title'] = $title;
                $itemarray['url'] = 'http://www.chong4.com.cn' . $url;
                $itemarray['onlyid'] = get_word($item, 'starid', '"');
                $itemarray['source'] = 0;
                if ($title && $url) {
                    $result['item_list'][] = $itemarray;
                }
            }
        }
        foreach ($result['item_list'] as $key => $val) {
            $res = $this->_ajax_tb_publish_insert($val);
            if ($res > 0) {
                $coll++;
                $order_num++;
            }
            $totalcoll++;
        }
        if ($p == $setting['page']) {
            $this->ajaxReturn(0, '已经采集完成' . $p . '页,本次采集到' . $order_num . '篇文章！请返回，谢谢');
        }
        F('totalcoll', $totalcoll);
        F('order_num', $order_num);
        $this->assign('p', $p);
        $this->assign('coll', $coll);
        $this->assign('order_num', $order_num);
        $this->assign('totalcoll', $totalcoll);
        $resp = $this->fetch('collect');
        $this->ajaxReturn(1, '穿衣搭配采集—爱淘客', $resp);
    }
    public function toutiao_collect()
    {
        $source = '';
        if (false === ($setting = F('toutiao_setting'))) {
            $this->ajaxReturn(0, L('illegal_parameters'));
        }
        $p = $this->_get('p', 'intval', 1);
        if ($p == 1) {
            $totalcoll = 0;
            $order_num = 0;
            $publishId = 0;
        } else {
            $totalcoll = F('totalcoll');
            $order_num = F('order_num');
            $publishId = F('publishId');
        }
        $coll = 0;
        $url = 'https://headline.taobao.com/feed/feedQuery.do?columnId=' . $setting['cat'] . '&publishId=' . $publishId . '&subColumn=' . urlencode($setting['keyword']);
        $itaoke_https = new \itaoke_https();
        $source = $itaoke_https->results;
        if (!$source) {
            $source = $this->curl_http($url);
        }
        $source = rtrim(ltrim(trim($source), '('), ')');
        $source = iconv('GBK', 'UTF-8//IGNORE', $source);
        $result_data = json_decode($source, true);
        if ($source) {
            for ($i = 0; $i < 20; $i++) {
                $title = $result_data['data'][$i]['name'];
                $url = $result_data['data'][$i]['detailUrl'];
                $mpic = $result_data['data'][$i]['picList'][0];
                $desc = $result_data['data'][$i]['description'];
                $itemarray['title'] = $title;
                $itemarray['url'] = $url;
                $itemarray['onlyid'] = $result_data['data'][$i]['feedId'];
                $itemarray['source'] = 1;
                $itemarray['mpic'] = $result_data['data'][$i]['picList'][0];
                if (strpos($url, 'headline.taobao.com')) {
                    $itemarray['desc'] = $result_data['data'][$i]['description'];
                } else {
                    $itemarray['desc'] = '';
                }
                if ($title && $url && $mpic) {
                    $result['article_list'][] = $itemarray;
                }
            }
            $last_array = end($result_data['data']);
            $publishId = $last_array['publishId'];
        }
        foreach ($result['article_list'] as $key => $val) {
            $res = $this->_ajax_tb_publish_insert($val);
            if ($res > 0) {
                $coll++;
                $order_num++;
            }
            $totalcoll++;
        }
        if ($p == $setting['page']) {
            $this->ajaxReturn(0, '已经采集完成' . $p . '页,本次采集到' . $order_num . '篇文章！请返回，谢谢');
        }
        F('totalcoll', $totalcoll);
        F('order_num', $order_num);
        F('publishId', $publishId);
        $this->assign('p', $p);
        $this->assign('coll', $coll);
        $this->assign('publishId', $publishId);
        $this->assign('order_num', $order_num);
        $this->assign('totalcoll', $totalcoll);
        $resp = $this->fetch('collect');
        $this->ajaxReturn(1, '淘宝头条采集 - 爱淘客', $resp);
    }
    private function _ajax_tb_publish_insert($item)
    {
        $item['title'] = trim(strip_tags($item['title']));
        $result = D('ArticleUrl')->ajax_aurl_publish($item);
        return $result;
    }
    private function curl_http($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
        curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}